/**
 * 
 */
package com.gmail.avereshchaga.web.validate;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author <a href="mailto:avereshchaga@gmail.com">Vereshchaga Alexey</a>
 * 
 */
public class BirthdateValidator implements
        ConstraintValidator<Birthdate, String> {

    private String message = Birthdate.MESSAGE;

    private Date date;

    protected Date now() {

        return new Date();
    }

    public void initialize(Birthdate constraintAnnotation) {
        this.message = constraintAnnotation.message();
    }

    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {

        try {
            DateFormat format = new SimpleDateFormat("dd.MM.yyyy");
            format.setLenient(false);
            date = format.parse(s);

        } catch (ParseException e) {
            return false;
        }
        Integer yearSmallestAvailable = 1900;
        String yearStr = s.substring(6);
        Integer yearOfBirth = Integer.parseInt(yearStr);
        if (!date.before(now()) || yearOfBirth < yearSmallestAvailable) {
            String msg = "Date less than 1900 year or more that currently";
            constraintValidatorContext.disableDefaultConstraintViolation();
            constraintValidatorContext.buildConstraintViolationWithTemplate(msg)
                    .addConstraintViolation();
            return false;
        }
        return true;
    }

}
